package syllabus.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;











import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import syllabus.commons.DateTypeEditor;
import syllabus.commons.ExtGridReturn;
import syllabus.commons.ExtPager;
import syllabus.commons.ExtReturn;
import syllabus.model.Criteria;
import syllabus.model.PCourse;
import syllabus.service.PCourseService;

@RequestMapping("/course")
@Controller
public class CourseAct {

	private static final Logger logger = LoggerFactory.getLogger(CourseAct.class);
	
	@Autowired
	private PCourseService courseService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateTypeEditor());
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}
	
	@RequestMapping("/list")
	public String list(){
		return "/course/list";
	}
	
	@RequestMapping(value = "/all", method = RequestMethod.POST)
	@ResponseBody
	public Object all(ExtPager pager,@RequestParam(required = false,value = "courseName")String courseName,
			ModelMap map) {
		Criteria criteria = new Criteria();
		// 设置分页信息
		if (pager.getPage() != null && pager.getRows() != null) {
			criteria.setPage(pager.getPage());
			criteria.setPageSize(pager.getRows());
		}
		// 排序信息
		if (StringUtils.isNotBlank(pager.getOrder())
				&& StringUtils.isNotBlank(pager.getSort())) {
			criteria.setOrderByClause(pager.getSort() + " " + pager.getOrder());
		}
		if (StringUtils.isNotBlank(courseName)) {
			criteria.put("courseNameLike", courseName);
		}
		
		List<PCourse> list = this.courseService.selectByExample(criteria);

		int total = this.courseService.countByExample(criteria);
		return new ExtGridReturn(total, list);
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(PCourse course,HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{
		ExtReturn ext = new ExtReturn();
		Integer courseId = course.getId();
		
		if (courseId != null && courseId > 0) {
			/**
			 * 编辑
			 */
			try {
				PCourse pc = courseService.selectByPrimaryKey(courseId);
				pc.setKcdm(course.getKcdm());
				pc.setKcjj(course.getKcjj());
				pc.setKclb(course.getKclb());
				pc.setKcywmc(course.getKcywmc());
				pc.setKczwmc(course.getKczwmc());
				pc.setKhfs(course.getKhfs());
				pc.setKkbmdm(course.getKkbmdm());
				pc.setLrsj(course.getLrsj());
				pc.setXf(course.getXf());
				pc.setXkfl(course.getXkfl());
				
				courseService.updateByPrimaryKeySelective(course);
				ext.setSuccess(true);
				ext.setMsg("更新成功！");
				
			} catch (Exception e) {
				ext.setSuccess(false);
				ext.setMsg("更新出错！");
				e.printStackTrace();
			}
		}else{
			/**
			 * 新增
			 */
			try {
				int n = courseService.insertSelective(course);
				ext.setSuccess(true);
				ext.setMsg("保存成功！");
				logger.info("新增课程  {}",course.getKczwmc());
			} catch (Exception e) {
				ext.setSuccess(false);
				ext.setMsg("保存出错！");
				e.printStackTrace();
			}
		}
		response.setContentType("text/plain;charset=utf-8");
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(),ext );
		
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(String id,HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{
		
		ExtReturn ex = new ExtReturn();
		if (StringUtils.isNotBlank(id)) {
			try {
				courseService.deleteByPrimaryKey(Integer.parseInt(id));
				logger.info("删除 讲座信息{}",id);
			} catch (Exception e) {
				e.printStackTrace();
				ex.setSuccess(false);
				ex.setMsg("删除出错！");
			}
		}
		ex.setSuccess(true);
		ex.setMsg("删除成功！");
		
		response.setContentType("text/plain;charset=utf-8");
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(),ex );
	}
	
	@RequestMapping(value = "/generate", method = RequestMethod.POST)
	public void generate(PCourse course,HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{
	
		ExtReturn ex = new ExtReturn();
		Criteria c = new Criteria();
		Integer courseId = course.getId();
		if (courseId != null && courseId > 0) {
			//根据id生成一个大纲
			c.put("courseId", courseId);
			
		}
		// 生成所有课程的大纲
		try {
			courseService.insertAllIntoSyllabus(c);
			ex.setSuccess(ExtReturn.SUCCESS);
			ex.setMsg("大纲生成成功");
		} catch (Exception e) {
			ex.setSuccess(ExtReturn.FAILURE);
			ex.setMsg("大纲生成失败");
			e.printStackTrace();
		}
		
		response.setContentType("text/plain;charset=utf-8");
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(),ex );
	}
}
